<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\Grid\BatchRestore;
use App\Admin\Actions\Grid\Restore;
use App\Admin\Repositories\Topic;
use App\Models\Tag;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Widgets\Markdown;
use HavenShen\EnjellyDown\Facades\EnjellyDown;
use Illuminate\Support\Arr;


class TopicController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Topic(), function (Grid $grid) {

            $grid->showColumnSelector();
            $grid->disableCreateButton();

            $user_id = intval(request('user_id'));
            if ($user_id) {
                $grid->model()->where('user_id', $user_id);
            }
            $tag_id = intval(request('tag_id'));
            if ($tag_id) {
                $grid->model()
                    ->join('topic_tag', 'topics.id', '=', 'topic_tag.topic_id')
                    ->where('topic_tag.tag_id', '=', $tag_id);
            }

            $grid->model()
                ->with(['user', 'tags', 'category', 'reply_user']);

            $grid->column('id')
                ->sortable()
                ->hide();

            $grid->column('title')
                ->display(function ($value) {
                    return '<a href="/topics/' . $this->id . '" target="_blank">' . $value . '</a>';
                });

            /*$grid->column('body')->hide()->display(function ($value) {
                return EnjellyDown::markdown($value);
            });*/

            $grid->column('user_id')
                ->sortable()
                ->display(function () {
                    return '<a href="/admin/topic?user_id=' . $this->user_id . '" title="用户话题">' . $this->user->name . '</a>';
                });

            $grid->column('category_id')
                ->sortable()
                ->display(function () {
                    return '<a href="/admin/topic?category_id=' . $this->category_id . '" title="分类话题">' . $this->category->name . '</a>';
                });

            $grid->column('tags')->display(function () {
                return $this->str_tags;
            });

            $grid->column('reply_count')
                ->sortable()
                ->display(function ($value) {
                    return '<a href="/admin/reply?topic_id=' . $this->id . '" title="话题回复">' . $value . '</a>';
                });

            $grid->column('view_count')
                ->sortable();

            $grid->column('last_reply_user_id')
                ->sortable()
                ->display(function () {
                    return $this->reply_user ? $this->reply_user->name : '';
                });

            $grid->column('order')
                ->sortable()
                ->editable();

            $grid->column('excerpt')
                ->hide();

            $grid->column('slug')
                ->hide();

            $grid->column('created_at')
                ->hide()
                ->sortable();

            $grid->column('updated_at')
                ->sortable();


            // 回收站
            $grid->filter(function (Grid\Filter $filter) {

                // 范围过滤器，调用模型的`onlyTrashed`方法，查询出被软删除的数据。
                $filter->scope('trashed', '回收站')->onlyTrashed();

                $filter->like('title');
                $filter->like('user.name', '用户');
                $filter->equal('category_id')->select(get_category_options());
                $filter->equal('tags.name', '标签');
            });
            // 行恢复
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                if (request('_scope_') == 'trashed') {
                    $actions->append(new Restore(\App\Models\Topic::class));
                }
            });
            // 批量恢复
            $grid->batchActions(function (Grid\Tools\BatchActions $batch) {
                if (request('_scope_') == 'trashed') {
                    $batch->add(new BatchRestore(\App\Models\Topic::class));
                }
            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {

        return Show::make($id, new Topic(), function (Show $show) {

            $show->html(function () {
                return '【' . $this->category->name . '】' . $this->title;
            });
            $show->divider();
            $show->html(function () {

                return '【发布人：' . $this->user->name . '】
                【回复数：' . $this->reply_count . '】
                【浏览量：' . $this->view_count . '】
                【标签：' . $this->str_tags . '】';
            });
            $show->divider();
            $show->html(function () {

                return <<<HTML

<div id="topic-body-md" class="topic-body mt-4 mb-4">
    <textarea class="d-none">{$this->body}</textarea>
</div>

HTML;

                // return EnjellyDown::markdown($this->body);
            });


            admin_css('/vendor/editor.md/css/editormd.preview.min.css');
            admin_js('/vendor/editor.md/editormd.min.js');
            admin_js('/vendor/editor.md/lib/flowchart.min.js');
            admin_js('/vendor/editor.md/lib/jquery.flowchart.min.js');
            admin_js('/vendor/editor.md/lib/marked.min.js');
            admin_js('/vendor/editor.md/lib/prettify.min.js');
            admin_js('/vendor/editor.md/lib/raphael.min.js');
            admin_js('/vendor/editor.md/lib/sequence-diagram.min.js');
            admin_js('/vendor/editor.md/lib/underscore.min.js');
            Admin::script(<<<SCRIPT

        $(function () {

            // 修正emoji图片错误
            editormd.emoji = {
                path: "//staticfile.qnssl.com/emoji-cheat-sheet/1.0.0/",
                ext: ".png"
            };
            var topicEditorMdView = editormd.markdownToHTML("topic-body-md", {
                // markdown : md,
                codeFold: true,
                syncScrolling: true,
                saveHTMLToTextarea: true,    // 保存 HTML 到 Textarea
                searchReplace: true,
                watch: true,                // 关闭实时预览
                htmlDecode: "style,script,iframe|on*",            // 开启 HTML 标签解析，为了安全性，默认不开启
                previewCodeHighlight: true, // 关闭预览 HTML 的代码块高亮，默认开启
                emoji: true,
                taskList: true,
                tocm: true,                  // Using [TOCM]
                tex: true,                   // 开启科学公式TeX语言支持，默认关闭
                flowChart: true,             // 开启流程图支持，默认关闭
                sequenceDiagram: true,       // 开启时序/序列图支持，默认关闭,
            });
        });
SCRIPT
            );
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(Topic::with('tags'), function (Form $form) {

            $form->width(12, 0);
            $form->hidden('id');
            $form->text('title', '')
                ->rules('required|min:2');

            $form->select('category_id', '')
                ->options(get_category_options())
                ->rules('required|numeric');

            $form->markdown('body', '')
                ->rules('required|min:3');

            $form->multipleSelect('tags', '')
                ->options(function ($ids) {
                    // 默认加载已选数据
                    if($ids){
                        return Tag::find($ids)->pluck('name', 'id');
                    }
                })
                ->customFormat(function ($tags) {
                    // 新增（或无数据）避免报错
                    if (! $tags) {
                        return [];
                    }
                    // 从数据库中查出的二维数组中转化成ID
                    return array_column($tags, 'id');
                })
                ->ajax('api/tags');

            $form->hidden('order')->rules('numeric');


        });
    }


}
